package com.woniuxy.third.controller;

import com.woniuxy.third.enyity.User;
import com.woniuxy.third.result.ResponseResult;
import com.woniuxy.third.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @RequestMapping("/login")
    public ResponseResult<String> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){
        System.out.println(request);
        //先判断是否登录状态
        String authorization = request.getHeader("authorization");
        if(authorization!=null){
            return new ResponseResult<>(201,"请勿重复登录",null);
        }
        //对接前段账号进行数据库比对
        if(user.getAccount().equals("zhangsan")&&user.getPwd().equals("123")){
            logger.debug("登录成功");
            //生成JWT token,然后返回前端
            String token = JwtUtil.generateToken(user.getAccount());
            //将token放在响应头
            response.setHeader("authorization",token);
            //将响应头暴露给第三方
            response.setHeader("Access-Control-Expose-Headers","authorization");
            return new ResponseResult<>(200,"success",null);
        }else{
            logger.debug("登录失败");
            return new ResponseResult<>(500,"fail",null);
        }
    }
}
